<template>
  <div class="serach-suggestion">
    <van-cell 
    icon="search" 
    v-for="(text,index) in suggestions" 
    :key="index"
    @click="$emit('search',text)"
    >
      <div slot="title" v-html="highlight(text)"></div>
    </van-cell>
   
  </div>
</template>

<script>
import {debounce} from 'lodash'  //用于处理防抖的插件
import {getSearchSuggestionAPI} from '@/api'


export default {
  name:'SearchSuggestion',
  props:{
    searchText:{
      type:String,
      required:true
    }
  },
  data(){
    return{
      suggestions:[]
    }
  },
  watch:{
    searchText:{
      // handler(val){
      //   this.getSearchSuggestions()
      // },
      //处理防抖
      handler:debounce(function(val){
        this.getSearchSuggestions()
      },200),
      immediate:true,
      deep:true
    }
  },
  methods:{
    //获取联想建议
    async getSearchSuggestions(){
      try{
        const {data}=await getSearchSuggestionAPI(this.searchText)
        this.suggestions=data.data.options
      }catch(err){
        this.$toast('数据获取失败,请稍后重试!')
      }
    },
    //处理文字高亮显示
    highlight(text){
      if(text){
      const highlightStr=`<span class="active">${this.searchText}</span>`
      //优点:可以动态设置规则
      const reg=new RegExp(this.searchText,'gi')
      return text.replace(reg,highlightStr)
      }
    }
  }

}
</script>

<style lang="less" scoped>
  .serach-suggestion{
    /deep/span.active{
      color: #b805fa;
    }
  }

</style>
